﻿namespace OnlineVideos.RingToneEditor
{
   
    using System;

    public class AcmMp3FrameDecompressor : IMp3FrameDecompressor, IDisposable
    {
        private AcmStream conversionStream;
        private WaveFormat pcmFormat;

        public AcmMp3FrameDecompressor(WaveFormat sourceFormat)
        {
            this.pcmFormat = AcmStream.SuggestPcmFormat(sourceFormat);
            this.conversionStream = new AcmStream(sourceFormat, this.pcmFormat);
        }

        public int DecompressFrame(Mp3Frame frame, byte[] dest, int destOffset)
        {
            Array.Copy(frame.RawData, this.conversionStream.SourceBuffer, frame.FrameLength);
            int sourceBytesConverted = 0;
            int length = this.conversionStream.Convert(frame.FrameLength, out sourceBytesConverted);
            if (sourceBytesConverted != frame.FrameLength)
            {
                throw new InvalidOperationException(string.Format("Couldn't convert the whole MP3 frame (converted {0}/{1})", sourceBytesConverted, frame.FrameLength));
            }
            Array.Copy(this.conversionStream.DestBuffer, 0, dest, destOffset, length);
            return length;
        }

        public void Dispose()
        {
            if (this.conversionStream != null)
            {
                this.conversionStream.Dispose();
                this.conversionStream = null;
            }
        }

        public WaveFormat OutputFormat
        {
            get
            {
                return this.pcmFormat;
            }
        }
    }
}

